package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.service.IDepartmentService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IDepartmentService departmentService;
    @Autowired
    private IRoleService roleService;

    @RequestMapping("/list")
    @RequirePermission(name = "员工查询", expression = "employee:list")
    public String list(Model model, @ModelAttribute("qo") EmployeeQueryObject qo) {
        // 分页查询 存到 model中 然后在前端显示
        model.addAttribute("pageInfo", employeeService.query(qo));
        // 部门 用于前端部门下拉框显示
        model.addAttribute("departments", departmentService.listAll());
        return "employee/list";
    }

    @RequestMapping("/input")
    // 编辑和添加用的同一个页面,所以这里表达式页和 saveOrUpdate 用同一个
    @RequirePermission(name = "员工编辑", expression = "employee:saveOrUpdate")
    public String input(Model model, Long id) {
        // 所有的角色  在角色框中回显
        model.addAttribute("roles", roleService.listAll());
        if (id != null) {
            model.addAttribute("employee", employeeService.get(id));
            // 查询员工的对应的角色存到model中
            model.addAttribute("ownRoles", roleService.queryByEmployeeId(id));
        }
        // 部门回显
        model.addAttribute("departments", departmentService.listAll());
        return "employee/input";
    }

    @RequestMapping("/delete")
    @RequirePermission(name = "员工删除", expression = "employee:delete")
    public String delete(Long id) {
        if (id != null) {
            employeeService.delete(id);
        }
        return "redirect:/employee/list";
    }

    @RequestMapping("/saveOrUpdate")
    @RequirePermission(name = "员工编辑", expression = "employee:saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Employee employee, Long[] roleIds) {
        try {
            if (employee.getId() != null) {
                employeeService.update(employee, roleIds);
            } else {
                employeeService.insert(employee, roleIds);
            }
            return new JsonResult(true, "编辑成功");
        } catch (Exception e) {
            return new JsonResult(false, "编辑失败");
        }
    }

    // 判断用户名是否被占用
    @RequestMapping("/checkUsername")
    @ResponseBody
    // 注意：插件要求返回结果需要为键值对形式 key 为 valid，value 为 boolean 类型
    public Map<String, Boolean> checkUsername(String username) {
        // 若存在 返回 true ,不存在 ,返回false
        boolean exist = employeeService.checkUsername(username);
        // 这里的data是 一个map对象
        Map<String, Boolean> data = new HashMap<>();
        data.put("valid", !exist); // 这里的valid为 true 表示 用户名没有被占用,所以要取反
        return data;
    }

    // 文件导出 =>文件下载
    @RequestMapping("/exportXls")
    public void exportXls(HttpServletResponse response) throws IOException {
        // 文件下载的响应头（让浏览器访问资源的的时候以下载的方式打开）
        response.setHeader("Content-Disposition", "attachment;filename=employee.xls");
        // 创建 excel 文件
        Workbook workbook = employeeService.exportXls();
        // 把 excel 的数据输出给浏览器
        workbook.write(response.getOutputStream());

    }

    // 文件导入 =>文件上传
    @RequestMapping("/importXls")
    public String importXls(MultipartFile file) throws IOException{
        // 若用户没有上传文件,直接就点了保存
        if (file.getSize() == 0) {
            return "redirect:/employee/list";
        }
        // xls文件 用 HSSFWorkbook
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        employeeService.importXls(wb);
        return "redirect:/employee/list";
    }

}
